package com.besall.allbase.view.activity.tools.AudioListActivity;



import android.util.Log;

import com.besall.allbase.common.utils.PcmUtils;
import com.besall.allbase.view.base.BasePresenter;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author ericshen
 * @time $ $
 */
public class AudioListPresenter extends BasePresenter <IAudioListActivity> implements IAudioListPresenter {
    PcmUtils pcmUtils;
    static String TAG = "AudioListPresenter";
    @Override
    public void player(AudioListActivity context,String path, int type ) {
//        ShowProgressDialog.wait.dismiss();
        Log.i(TAG, "player: cur-----" + path);
        pcmUtils = PcmUtils.getInstant();
        //直接播放
        byte[] decodeData = getbytesFromeLocalFile(path);
        Log.i(TAG, "player: ++++" + decodeData);
        pcmUtils.resetPcmFile();
        pcmUtils.stopPlay();
        pcmUtils.addData(context, decodeData);
        pcmUtils.play(type);

    }

    public void stopplay(String path) {
        Log.i(TAG, "stopplay: " + path);
        pcmUtils.stopPlay();
    }

    //将本地文件转化为byte[]
    private byte[] getbytesFromeLocalFile(String path) {
        byte[] bytes = new  byte[]{};
        try {
            InputStream in = new FileInputStream(path);
            bytes = toByteArray(in);
            in.close();
        } catch (IOException e) {
            Log.i(TAG, "++++" + e.toString());
            e.printStackTrace();
        }
        return bytes;
    }

    private byte[] toByteArray(InputStream in) throws IOException {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer, 0, n);
        }
        return out.toByteArray();
    }
}
